//
//  AroundTableViewController.m
//  SXH
//
//  Created by Jack on 15/7/8.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "AroundTableViewController.h"
#import "AppDelegate.h"
#import "AroundTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "nearTableViewCell.h"
#import "Colours.h"
#import "YYAnimationIndicator.h"
#import "UIView+AutoLayout.h"

@interface AroundTableViewController ()<DPRequestDelegate>
{
    YYAnimationIndicator *indicator;
}
@end

@implementation AroundTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = @"周边";
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIButton *backButton =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [backButton setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    
    UIButton *btn1 =[[UIButton alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width/3 - 10, 40)];
    [btn1 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    [btn1 setBackgroundImage:[UIImage imageNamed:@"餐饮美食"] forState:UIControlStateNormal];
    btn1.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn1.tag = 0;
    
    UIButton *btn2 =[[UIButton alloc] initWithFrame:CGRectMake(10 + self.view.frame.size.width/3, 10, self.view.frame.size.width/3 - 10, 40)];
    [btn2 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 setBackgroundImage:[UIImage imageNamed:@"酒店住宿"] forState:UIControlStateNormal];
    btn2.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn2.tag = 1;
    
    UIButton *btn3 =[[UIButton alloc] initWithFrame:CGRectMake(10 + self.view.frame.size.width/2, 10, self.view.frame.size.width/3 - 10, 40)];
    [btn3 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    [btn3 setBackgroundImage:[UIImage imageNamed:@"娱乐休闲"] forState:UIControlStateNormal];
    btn3.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn3.tag = 2;
    
    [self.tableView addSubview:btn1];
    [self.tableView addSubview:btn2];
    [self.tableView addSubview:btn3];
    
    self.tableView.frame = CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height - 40);
    
    DebugLog(@"%f, %f", self.view.frame.size.width, self.view.frame.size.height);
    [self loadArroundData:0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.mutableArrayBusiness count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
    if (NSFoundationVersionNumber>NSFoundationVersionNumber_iOS_7_1) {
        return UITableViewAutomaticDimension;
    }
    */
    return 100;
}

- (void)request:(DPRequest *)request didFailWithError:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        [indicator stopAnimationWithLoadText:LoadFail_Text withType:YES];
    });
}

- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result {
    DebugLog(@"%@",[result description]);
    
    NSArray *businesses = [result objectForKey:@"businesses"];
 
    self.mutableArrayBusiness = [NSMutableArray arrayWithArray:businesses];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
        [self.tableView reloadData];
    });
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /*
    static NSString *couponTableViewCellIdentifier=@"AroundTableViewCell";
    [tableView registerNib:[UINib nibWithNibName:@"AroundTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:couponTableViewCellIdentifier];
    AroundTableViewCell *cell = (AroundTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    
    // Configure the cell...
    NSDictionary *dic = [self.mutableArrayBusiness objectAtIndex:indexPath.row] ;
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"photo_url"]];
    [cell.imageView setImageWithURL:url];
    
    cell.labelTitle.text = [dic objectForKey:@"name"];
    cell.labelAddress.text = [dic objectForKey:@"address"];
    
    NSNumber *price = [dic objectForKey:@"avg_price"];
    cell.labelPrice.text = [NSString stringWithFormat:@"¥%@",price];
    
    
    cell.labelDistance.text = [NSString stringWithFormat:@"%@米",distance];
    */
    
    [tableView registerClass:[nearTableViewCell class] forCellReuseIdentifier:@"nearTableViewCell"];
    //nearTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearTableViewCell" forIndexPath:indexPath];
    nearTableViewCell *cell  = [[nearTableViewCell alloc] init];
    NSDictionary *dic = [self.mutableArrayBusiness objectAtIndex:indexPath.row] ;
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"photo_url"]];
    [cell.myImageView sd_setImageWithURL:url];
    NSNumber *avg_rating = [dic objectForKey:@"avg_rating"];
    cell.myRating.rating = [avg_rating doubleValue];
    
    NSNumber *has_coupon = [dic objectForKey:@"has_coupon"];
    if ([has_coupon intValue]) {
        //[cell.myTagList addTag:@"惠"];
        [cell.myTagList addTag2:@"惠" colour:[UIColor carrotColor]];
    }
    
    NSNumber *has_deal = [dic objectForKey:@"has_deal"];
    if ([has_deal intValue]) {
        //[cell.myTagList addTag:@"团"];
        [cell.myTagList addTag2:@"团" colour:[UIColor cantaloupeColor]];
    }
    
    NSNumber *has_online_reservation = [dic objectForKey:@"has_online_reservation"];
    if ([has_online_reservation intValue]) {
        //[cell.myTagList addTag:@"订"];
        [cell.myTagList addTag2:@"订" colour:[UIColor seafoamColor]];
    }
    
    NSArray *categories = [dic objectForKey:@"categories"];
    NSMutableString *tagsString = [[NSMutableString alloc] init];
    
    for (NSString *aTag in categories) {
        [tagsString appendString:aTag];
        [tagsString appendString:@" "];
    }
    
    cell.myTags.text = tagsString ;
    cell.name.text = [dic objectForKey:@"name"];
    
    NSNumber *distance = [dic objectForKey:@"distance"];
    double theDistance = [distance doubleValue];
    
    cell.distance.text = [NSString stringWithFormat:@"%.2fkm",theDistance/1000.0];
//    if (theDistance>=1000) {
//        
//    } else{
//        cell.distance.text = [NSString stringWithFormat:@"%@m",distance];
//    }
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void) goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) loadArroundData:(int) category {
    
    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
    [indicator setLoadText:Loading_Text];
    [self.view addSubview:indicator];
    
    [indicator startAnimation];  //开始转动
    
    NSString *url = @"v1/business/find_businesses";
    
    NSString *params = @"";
    if (category == 0) {
        params = [NSString stringWithFormat:@"latitude=32.410486&longitude=119.428585&category=酒店&sort=2&limit=30"];
    } else if (category == 1) {
        params = [NSString stringWithFormat:@"latitude=32.410486&longitude=119.428585&category=住宿&sort=2&limit=30"];
    } else {
        params = [NSString stringWithFormat:@"latitude=32.410486&longitude=119.428585&category=娱乐&sort=2&limit=30"];
    }
    
    [[[AppDelegate instance] dpapi] requestWithURL:url paramsString:params delegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AroundTableViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AroundTableViewController"];
}
@end
